package com.borya.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.borya.constant.RedisConstant;
import com.borya.dao.SdkNotifyDAO;
import com.borya.framework.annotation.Component;
import com.borya.framework.core.ServerSqlSession;
import com.borya.model.db.ModelInfo;
import com.borya.model.db.SdkDeviceConf;
import com.borya.model.db.SdkMerchant;
import com.borya.model.db.SdkMerchantAccount;


@Component("sdkNotifyDAO")
public class SdkNotifyDAOImpl extends BaseDAOImpl implements SdkNotifyDAO{

	
	private Logger log = Logger.getLogger(getClass());
	
	@Override
	public List<String> brpop(final String key) {
		return redis_brpop(RedisConstant.REDIS_TIMEOUT_SECOND, key);
	}
	
	@Override
	public Object[] get(final String appId,final String defaultDealerId,String packageId) {
		try(ServerSqlSession session = getSqlDataSource().session();){
			StringBuilder sql = new StringBuilder(128);
			sql.append("SELECT appid,app_key,company_name,user_name,phone");
			sql.append(" from sdk_merchant");
			sql.append(" where appid=? ");
			sql.append(" limit 1");
			SdkMerchant merchant = session.executeQuery(sql.toString(), rs-> {
				if(rs != null && rs.next()){
					SdkMerchant merchantTmp = new SdkMerchant();
					merchantTmp.setAppId(appId);
					merchantTmp.setAppKey(rs.getString("app_key"));
					merchantTmp.setCompanyName(rs.getString("company_name"));
					merchantTmp.setUserName(rs.getString("user_name"));
					merchantTmp.setPhone(rs.getString("phone"));
					return merchantTmp;
				}
				log.warn("DB not found sdk info(sdk_merchant),appid="+appId);
				return null;
			}, appId);
			if(merchant == null){
				return new Object[]{};
			}
			
			sql.delete(0, sql.length());
			sql.append("select phone_model,discount_model,create_time");
			sql.append(" from tb_model_info");
			sql.append(" where dealer_id=?");
			ModelInfo info = session.executeQuery(sql.toString(), rs-> {
				if(rs != null && rs.next()){
					ModelInfo infoTmp = new ModelInfo();
					infoTmp.setPhoneModel(rs.getString("phone_model"));
					infoTmp.setDiscountModel(rs.getString("discount_model"));
					infoTmp.setCreateTime(rs.getLong("create_time"));
					infoTmp.setDealerId(defaultDealerId);
					
					return infoTmp;
				}
				log.warn("DB nont found package(tb_model_info),dealer_id="+defaultDealerId);
				return new ModelInfo();
			} ,defaultDealerId);
			
			sql.delete(0, sql.length());
			sql.append("select iccid_model,deviceId");
			sql.append(" from sdk_device_conf");
			sql.append(" where packege_id=? ");
			sql.append(" limit 1");
			SdkDeviceConf conf = session.executeQuery(sql.toString(), rs-> {
				if(rs != null && rs.next()){
					SdkDeviceConf confTmp = new SdkDeviceConf();
					confTmp.setPackageId(packageId);
					confTmp.setDeviceId(rs.getString("deviceId"));
					confTmp.setIccidModel(rs.getString("iccid_model"));
					return confTmp;
				}
				log.warn("DB nont found package(sdk_device_conf),packege_id="+packageId);
				return new SdkDeviceConf();
			},packageId);
			return new Object[]{merchant,info,conf };
		}catch(Exception ex){
			log.error(ex.getMessage(), ex);
			return new Object[]{};
		}
	}

	@Override
	public boolean savebatch(SdkMerchantAccount account, SdkMerchant merchant,SdkDeviceConf info) {
		List<String> list_sql = new ArrayList<String>();
		StringBuilder sb = new StringBuilder(256);
		sb.append("insert into sdk_merchant_account");
		sb.append("(appid,dealer_id,left_fee,freeze_fee,credit,overdraft,create_time");
		sb.append(")values(");
		sb.append("'"+account.getAppId()+"','"+account.getDealerId()+"'");
		sb.append(",'"+account.getLeftFee()+"','"+account.getFreezeFee()+"'");
		sb.append(",'"+account.getCredit()+"','"+account.getOverDraft()+"'");
		sb.append(",'"+account.getCreateTime()+"'");
		sb.append(");");
		list_sql.add(sb.toString());
		
		sb.delete(0, sb.length());
		sb.append("update sdk_merchant set ");
		sb.append(" dealer_id='"+merchant.getDealerId()+"'");
		sb.append(",popchannel='"+merchant.getPopChannel()+"'");
		sb.append(",discount_model='"+merchant.getDiscountModel()+"'");
		sb.append(",phone_model='"+merchant.getPhoneModel()+"'");
		sb.append("where appid='"+merchant.getAppId()+"'");
		list_sql.add(sb.toString());
		
		sb.delete(0, sb.length());
		sb.append("insert into sdk_device_conf");
		sb.append("(packege_id,iccid_model,deviceId,appid");
		sb.append(")values(");
		sb.append("'"+info.getPackageId()+"','"+info.getIccidModel()+"'");
		sb.append(",'"+info.getDeviceId()+"','"+info.getAppId()+"'");
		sb.append(")");
		list_sql.add(sb.toString());
		sb.delete(0, sb.length());
		sb = null;
		int[] result = executeBatch(list_sql);
		return result != null && result.length>0;
	}

	@Override
	public boolean modifyAccount(final SdkMerchantAccount account,SdkDeviceConf conf) {
		List<String> list = new ArrayList<String>();
		
		StringBuilder sql = new StringBuilder(128);
		sql.append("update sdk_merchant_account set");
		sql.append(" left_fee=left_fee+"+account.getLeftFee());
		sql.append(" where appid='"+account.getAppId()+"';");
		list.add(sql.toString());
		
		sql.delete(0, sql.length());
		sql.append("update sdk_device_conf set ");
//		sql.append(" flag="+conf.getFlag());
		sql.append(",appid='"+conf.getAppId()+"'");
		sql.append(" where packege_id='"+conf.getPackageId()+"';");
		list.add(sql.toString());
		
		int [] result = executeBatch(list);
		return result != null && result.length>0;
	}
	
}